﻿using AiBLSmartEdu.Module.AIMedicalAssistant.API.Configurations;
using ChromaDB.Client;
using FrameworkCore.DI;
using iText.Kernel.XMP.Options;
using Microsoft.Extensions.Options;

#nullable disable

namespace AiBLSmartEdu.Module.AIMedicalAssistant.API.Services;

public class ChromaClientService : IDisposable, ITransientDependency
{
    private readonly HttpClient _httpClient;
    private readonly ChromaConfigurationOptions _config;
    private ChromaCollectionClient _collectionClient;

    public ChromaClientService(IOptions<ChromaSettings> options)
    {
        // 配置基础参数
        _config = new ChromaConfigurationOptions(uri: options.Value.ApiUrl);
        _httpClient = new HttpClient();
    }

    private async Task InitializeCollection(string collectionName)
    {
        var client = new ChromaClient(_config, _httpClient);
        var collection = await client.GetOrCreateCollection(collectionName);
        _collectionClient = new ChromaCollectionClient(collection, _config, _httpClient);
    }

    public ChromaCollectionClient GetCollectionClient(string collectionName)
    {
        InitializeCollection(collectionName).Wait();
        return _collectionClient ?? throw new NullReferenceException("集合客户端未初始化");
    }

    public void Dispose()
    {
        _httpClient.Dispose();
        _collectionClient = null;
    }
}
